﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Lidgren.Network;

namespace NetworkDemo
{
    public class Player
    {
        #region Properties

        bool dirty = false;
        public bool Dirty
        {
            get { return dirty; }
            set { dirty = value; }
        }

        Sprite mySprite;
        public Sprite MySprite
        {
            get { return mySprite; }
            internal set { mySprite = value; }
        }

        string myName;
        public string MyName
        {
            get { return myName; }
            set { if (value.Length == 0) return; myName = value; }
        }

        int myNumber;
        public int MyNumber
        {
            get { return myNumber; }
            internal set { if (value < 1) return; myNumber = value; }
        }
        #endregion
        #region Init
        public Player(Texture2D spriteTex, string name, int number, Vector2 pos)
        {
            MySprite = new Sprite(spriteTex, pos, Vector2.One, Vector2.Zero, Layer.Mob);
            MyName = name;
            MyNumber = number;
        }
        #endregion
        #region Draw & Update
        public void Draw(GameTime gameTime, SpriteBatch spriteBatch, SpriteFont spriteFont)
        {
            MySprite.Draw(spriteBatch);
            DrawName(spriteBatch, spriteFont);
        }


        public void DrawName(SpriteBatch spriteBatch, SpriteFont spriteFont)
        {
            Vector2 fontOrigin = spriteFont.MeasureString(MyName) / 2;
            Vector2 fontPos = Vector2.Clamp(new Vector2(MySprite.Position.X + (fontOrigin.X / 2), MySprite.Position.Y - spriteFont.LineSpacing), 
                                            fontOrigin, 
                                            new Vector2(1280.0f, 1024.0f) - fontOrigin);
            spriteBatch.DrawString(spriteFont, MyName, fontPos, Color.Black, 0, fontOrigin, 1.0f, SpriteEffects.None, (float)Layer.Fly / 100.0f);
        }
        #endregion

        #region network
        public static void WriteBuffer(Player P, NetBuffer buff)
        {
            buff.Write(P.MyNumber, 3);
            buff.Write(P.MySprite.Position.X);
            buff.Write(P.MySprite.Position.Y);
            buff.Write(P.MyName);
        }

        public static void WriteBuffer(int pNum, Vector2 pPos, string pName, NetBuffer buff)
        {
            buff.Write(pNum, 3);
            buff.Write(pPos.X);
            buff.Write(pPos.Y);
            buff.Write(pName);
        }
        #endregion
    }
}